package cn.com.swu.mianyangapp.ui.news;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.FileUtils;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import cn.com.swu.mianyangapp.R;
import cn.com.swu.mianyangapp.ui.bean.News;
import cn.com.swu.mianyangapp.ui.bean.NewsType;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class NewsAddActivity extends AppCompatActivity {

    private String user = "likang";
    private int userid = 1;

    final private String mIp = "192.168.58.15:8081";

    private News mNews;
    private EditText mEditTextName;
    private RadioGroup mRadioGroupStatus;
    private RadioGroup mRadioGroupallow;
    private Spinner mSpinner;
    private ImageView mImageView;
    private EditText mEditTextContext;

    private Button mButtonAdd;
    private Button mButtonCancel;
    private static Handler mHandler1;
    private static Handler mHandler2;
    private String Tag = "OKHttp_Add";
    ActivityResultLauncher<Intent> mResultLauncher;
    private String SpinnerData;

    private int mNewsStatus;
    private int mNewsAllow;
    private File imageFile;

    @SuppressLint("HandlerLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_add);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        ActionBar supportActionBar = getSupportActionBar();
        supportActionBar.setDisplayHomeAsUpEnabled(true);
        Intent intent = getIntent();
        mNews = (News) intent.getSerializableExtra("News");
        initView();
        initData();
        supportActionBar.setTitle("新建新闻");
        if (mNews.getNews_name() != null){
            supportActionBar.setTitle("修改新闻");
            mEditTextName.setText(mNews.getNews_name());
            mEditTextContext.setText(mNews.getNews_context());
            if (mNews.getNews_allow() == 0){
                RadioButton radioButton = findViewById(R.id.news_allow_false);
                radioButton.setChecked(true);
            }
            if (mNews.getNews_status() == 1){
                RadioButton radioButton = findViewById(R.id.news_status_1);
                radioButton.setChecked(true);
            }
            if (mNews.getNews_image_name() != null) {
                getBitImage(mNews.getNews_image_name());
                mHandler2 = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        Bitmap bitmap = (Bitmap) msg.obj;
                        mImageView.setImageBitmap(bitmap);
                    }
                };
            }
        }
        mHandler1 = new Handler(){
            @Override
            public void handleMessage(Message msg) {

                List<String> all = new ArrayList<String>();
                List<NewsType> list = new ArrayList<NewsType>();
                list = (List<NewsType>)msg.obj;
                for(int i=0;i<list.size();i++){
                    all.add(list.get(i).getNews_type_name());
                }
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(NewsAddActivity.this, R.layout.news_type_item, all);
                mSpinner.setAdapter(adapter);
                mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                    @Override
                    public void onItemSelected(AdapterView<?> adapterView, View view,
                                               int position, long id) {
                        //获取选中值
                        Spinner spinner = (Spinner) adapterView;
                        SpinnerData = (String) spinner.getItemAtPosition(position);

                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                    }

                });
            }
        };
        mResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == RESULT_OK){
                    Intent intent = result.getData();
                    Uri picUri = intent.getData();
                    if(picUri != null){
                        mImageView.setImageURI(picUri);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                            imageFile = uriToFileApiQ(picUri,NewsAddActivity.this);
                        }

                    }
                }
            }
        });
        mImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                mResultLauncher.launch(intent);
            }
        });

        mButtonCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mRadioGroupStatus.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = (RadioButton) findViewById(group.getCheckedRadioButtonId());
                String selectText = radioButton.getText().toString();
                if (selectText.equals("草稿")){
                    mNewsStatus = 0;
                }
                else {
                    mNewsStatus = 1;
                }
            }
        });
        mRadioGroupallow.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = (RadioButton) findViewById(group.getCheckedRadioButtonId());
                String selectText = radioButton.getText().toString();
                if (selectText.equals("否")){
                    mNewsAllow = 0;
                }
                else {
                    mNewsAllow = 1;
                }
            }
        });
        mButtonAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String newsName = mEditTextName.getText().toString();
                Log.e(Tag,newsName);
                int newsStatus = mNewsStatus;

                int newsAllow = mNewsAllow;

                String newsType = SpinnerData;
                Log.e(Tag,"newsType" + newsType + "status" + newsStatus + "allow" + newsAllow);
                String newsContext = mEditTextContext.getText().toString();
                OkHttpClient client = new OkHttpClient();
                RequestBody formBody;
                if (imageFile != null){
                    RequestBody fileBody = RequestBody.create(MediaType.parse("image/png"), imageFile);
                    formBody = new MultipartBody.Builder()
                            .setType(MultipartBody.FORM)
                            .addFormDataPart("news_name",newsName)
                            .addFormDataPart("news_status", String.valueOf(newsStatus))
                            .addFormDataPart("news_belong", newsType)
                            .addFormDataPart("news_context",newsContext)
                            .addFormDataPart("news_file",imageFile.getName(),fileBody)
                            .addFormDataPart("news_top", String.valueOf(0))
                            .addFormDataPart("news_allow", String.valueOf(newsAllow))
                            .build();
                }else {
                    formBody = new MultipartBody.Builder()
                            .setType(MultipartBody.FORM)
                            .addFormDataPart("news_name",newsName)
                            .addFormDataPart("news_status", String.valueOf(newsStatus))
                            .addFormDataPart("news_belong", newsType)
                            .addFormDataPart("news_context",newsContext)
                            .addFormDataPart("news_top", String.valueOf(0))
                            .addFormDataPart("news_allow", String.valueOf(newsAllow))
                            .build();
                }


                Request request;
                if (mNews.getNews_name() != null) {
                    request = new Request.Builder()
                            .url("http://" + mIp + "/change_news/" + mNews.getNews_id() +"/" + user + "/" + userid)
                            .post(formBody)
                            .build();
                }
                else {
                    request = new Request.Builder()
                            .url("http://" + mIp + "/add_news/" + user + "/" + userid)
                            .post(formBody)
                            .build();
                }
                Log.e(Tag,request.url().toString());
                Call call = client.newCall(request);
                try {
                    Response response = call.execute();
                    Log.e(Tag, response.toString());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                finish();


            }
        });

    }

    private void initView(){
        mEditTextName = findViewById(R.id.news_name_add);
        mRadioGroupallow = findViewById(R.id.news_allow_box);
        mEditTextContext = findViewById(R.id.add_content);
        mImageView = findViewById(R.id.news_add_image);
        mRadioGroupStatus = findViewById(R.id.news_status_box);
        mButtonAdd = findViewById(R.id.news_add_button);
        mButtonCancel = findViewById(R.id.news_cancel_button);
        mSpinner = findViewById(R.id.news_type_add);
    }

    private void initData() {
        OkHttpClient client = new OkHttpClient();
        FormBody body = new FormBody.Builder().build();
        Request request = new Request.Builder()
                .url("http://" +mIp +  "/news_type_query")
                .addHeader("Accept-Language","zh-CN,zh;q=0.9")
                .post(body)
                .build();

        Call call = client.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                Log.e(Tag,e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                JSONArray jsonArray = JSON.parseArray(result);
                List<NewsType> list = JSONObject.parseArray(jsonArray.toJSONString(), NewsType.class);

                Message msg = Message.obtain();
                Log.e(Tag,list.get(0).getNews_type_name());
                msg.obj = list; // 消息内存存放
                mHandler1.sendMessage(msg);
            }
        });

    }

    /**
     * user转换为file文件
     *返回值为file类型
     * @param uri
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.Q)
    public static File uriToFileApiQ(Uri uri, Context context) {
        File file = null;
        if(uri == null) return file;
        //android10以上转换
        if (uri.getScheme().equals(ContentResolver.SCHEME_FILE)) {
            file = new File(uri.getPath());
        } else if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
            //把文件复制到沙盒目录
            ContentResolver contentResolver = context.getContentResolver();
            String displayName = System.currentTimeMillis()+ Math.round((Math.random() + 1) * 1000)
                    +"."+ MimeTypeMap.getSingleton().getExtensionFromMimeType(contentResolver.getType(uri));

//            注释掉的方法可以获取到原文件的文件名，但是比较耗时
//            Cursor cursor = contentResolver.query(uri, null, null, null, null);
//            if (cursor.moveToFirst()) {
//                String displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));}

            try {
                InputStream is = contentResolver.openInputStream(uri);
                File cache = new File(context.getCacheDir().getAbsolutePath(), displayName);
                FileOutputStream fos = new FileOutputStream(cache);
                FileUtils.copy(is, fos);
                file = cache;
                fos.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }
    private void getBitImage(String news_image_name) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://" + mIp +"/"+news_image_name)
                .build();

        Call call = client.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                Log.e(Tag,e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream inputStream = response.body().byteStream();//得到图片的流
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                Message msg = new Message();
                msg.obj = bitmap;
                mHandler2.sendMessage(msg);

            }
        });
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        finish();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish(); // back button
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}